//
//  File.swift
//
//
//  Created by didi on 2022/9/13.
//

import MolecularObjects
import Vapor

public struct RequestValidator {
    public var validators: [AsyncValidator]

    public init(_ validators: [AsyncValidator] = []) {
        self.validators = validators
    }

    /// this is magic, don't touch it
    public func validate(_ req: Request, message: String? = nil) async throws {
        var result: [ErrorDetail] = []
        try await validators.forEachAsync { validator in
            if result.contains(where: { $0.key == validator.key }) { return }
            if let res = try await validator.validate(req) {
                result.append(res)
            }
        }

        if !result.isEmpty {
            throw ValidationAbort(abort: .init(.badRequest, reason: message), details: result)
        }
    }

    public func isValid(_ req: Request) async -> Bool {
        do {
            try await validate(req, message: nil)
            return true
        } catch {
            return false
        }
    }
}
